package slap.server;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory;
import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.logging.Slf4JLoggerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import slap.Slap;

import java.io.File;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Properties;
import java.util.concurrent.Executors;

public class NettyServer {
	protected static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
	public static int httpPort;
	public static int httpsPort;
	
	public ServerBootstrap bootstrap;
	
	public NettyServer() {
		System.setProperty("file.encoding", "utf-8");
		httpPort = Integer.valueOf(Slap.port);
		InternalLoggerFactory.setDefaultFactory(new Slf4JLoggerFactory());
		//TODO newFixedThreadPool
		bootstrap = new ServerBootstrap(
				new NioServerSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool())
		);
		bootstrap.setPipelineFactory(new HttpChannelPipelineFactory());
		bootstrap.setOption("child.tcpNoDelay", true);
		bootstrap.setOption("child.keepAlive", true);
		bootstrap.setOption("child.receiveBufferSize", 1048576);
	}

	public void start() {
		try {
			bootstrap.bind(new InetSocketAddress(httpPort));
			logger.info("Listening for HTTP at {}:{} (Waiting a first request to start) ...",
					httpPort, "localhost");
		} catch (ChannelException e) {
			logger.error("Could not bind on port {}", httpPort, e);
			System.exit(-1);
		}
		
	}

}
